/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.frontend;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;

import edu.pitt.cs3530.regression.TimeStamp;
import edu.pitt.cs3530.regression.TimeStamp.SecMSec;

/**
 * This class runs periodically and deletes files that exist outside of the time
 * window that we care about. That is to say, if we're calculating based on a
 * ten second past time window and a request came in eleven seconds ago, that
 * request information gets deleted
 */
public class DeleteOldFilesThread extends Thread {

	private BufferedWriter writer;
	private String directory;
	private long sleepTime;
	private long oldTime;
	int i = 0;

	/**
	 * @param directory
	 *            The directory requests are stored in
	 * @param sleepTime
	 *            The amount of time we should sleep for
	 * @param oldTime
	 *            The time window that we care about
	 */
	public DeleteOldFilesThread(String directory, long sleepTime, long oldTime) {
		this.directory = directory;
		this.sleepTime = sleepTime;
		this.oldTime = oldTime;
		try {
			writer = new BufferedWriter(new FileWriter("output.txt"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (true) {
				File dir = new File(directory);
				// System.out.println(dir);
				StringTokenizer tok = null;
				SecMSec ts = TimeStamp.createSecUSec();
				long currentTime = ts.getSec() * 1000 + ts.getMSec();
				// Mutexs.lockFileMutex();
				File[] files = dir.listFiles();
				// Mutexs.unlockFileMutex();
				int count = 0;
				for (File f : files) {
					if (f.getName().startsWith("fin-")) {
						tok = new StringTokenizer(f.getName(), "-");
						tok.nextToken();
						tok.nextToken();
						tok.nextToken();
						long sec = Long.parseLong(tok.nextToken());
						long mSec = Long.parseLong(tok.nextToken()) / 1000;
						long fileTime = sec * 1000 + mSec;
						if (fileTime + oldTime < currentTime) {
							try {
								log(f.getName());
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							f.delete();
							count++;
						}
					}
				}
				// System.out.println("Deleted: " + count);
				sleep(sleepTime);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void log(String filename) throws IOException {
		writer.write(filename);
		writer.write("\r\n");
		writer.flush();
	}
}
